package main

import (
	"net"
	"strings"
)

type User struct {
	Name   string
	Addr   string
	C      chan string
	conn   net.Conn
	Server *Server
}

//NewUser 创建一个用户
func NewUser(conn net.Conn, server *Server) *User {
	userAddr := conn.RemoteAddr().String()
	user := &User{
		Name:   userAddr,
		Addr:   userAddr,
		C:      make(chan string),
		conn:   conn,
		Server: server, //当前用户属于那个server
	}
	go user.ListenMessage()
	return user
}

//ListenMessage 监听当前管道中的 消息，一旦有消息 就发送到客户端
func (this *User) ListenMessage() {
	for {
		msg := <-this.C
		//发送消息(加换行)
		//rw *bufio.ReadWriter
		_, _ = this.conn.Write([]byte(msg + "\n"))
	}
}

func (this *User) Online() {
	//用户上线，将用户加入 oneLine
	this.Server.mapLock.Lock()
	this.Server.OnlineMap[this.Name] = this
	this.Server.mapLock.Unlock()
	//广播当前用户上线
	this.Server.BroadCast(this, "已上线")
}

func (this *User) Offline() {
	this.Server.mapLock.Lock()
	delete(this.Server.OnlineMap, this.Name)
	this.Server.mapLock.Unlock()
	//广播当前用户上线
	this.Server.BroadCast(this, "下线")
}

//SendMsg 给当前用户发送消息
func (this *User) SendMsg(msg string) {
	this.conn.Write([]byte(msg + "\n"))
}

func (this *User) DoMessage(msg string) {
	if msg == "who" {
		//查询当前在线用户并返回
		onlineMap := this.Server.OnlineMap
		for _, user := range onlineMap {
			onlineMsg := "[" + user.Addr + "]" + user.Name + " is online "
			//if this != user {
			this.SendMsg(onlineMsg)
			//this.C <- onlineMsg
			//}
		}
	} else if strings.HasPrefix(msg, "rename|") {
		//修改名字|消息格式[rename|zhangsan]
		newName := strings.Split(msg, "|")[1]
		_, ok := this.Server.OnlineMap[newName]
		if ok {
			this.SendMsg("当前用户名被使用了")
		} else {
			this.Server.mapLock.Lock()
			delete(this.Server.OnlineMap, this.Name)
			this.Server.OnlineMap[newName] = this
			this.Server.mapLock.Unlock()
			this.Name = newName
			this.SendMsg("已经更新用户名:" + newName)
		}
	} else if strings.HasPrefix(msg, "to|") {
		//私聊
		// 消息个是你 to|对方用户|消息内容
		msgToUser := strings.Split(msg, "|")
		remoteName := msgToUser[1]
		if strings.EqualFold(remoteName, "") {
			this.SendMsg("消息格式不正确，请使用[to|张三|你好啊]")
			return
		}
		remoteUser, ok := this.Server.OnlineMap[remoteName]
		if !ok {
			this.SendMsg("该用户不存在")
			return
		}
		content := msgToUser[2]
		if content == "" {
			this.SendMsg("无消息内容，请重发")
			return
		}
		remoteUser.SendMsg(this.Name + " --> " + remoteName + " msg=|" + content)
	} else {
		this.Server.BroadCast(this, msg)
	}
}
